-- DraculaCastleM
-- Created by chengb Nov/9/2015
-- 德古拉城堡相关逻辑

module("DraculaCastleM", package.seeall);

local PURE_FILE = "DraculaCastleM";

-- 是否解锁了德古拉的展柜
function hasUnlockedShowcase()
    return DungeonM.getDungeonMixedField("unlock_showcase") == 1;
end

-- 解锁德古拉的展柜
function unlockShowcase(pos)
    local grid = DungeonM.getGridByPos(pos);
    if not grid then
        trace(PURE_FILE, "格子(%d)不存在。", pos);
        return false;
    end

    local dbase = DungeonM.query(grid.class, "dbase");
    local sealItemId  = dbase["seal_item"];

    if ItemM.getAmount(ME.user, sealItemId) < 1 then
        trace(PURE_FILE, "无法解锁德古拉的展柜：没有道具(%d)", sealItemId);
        return false;
    end

    -- 已经解锁
    if hasUnlockedShowcase() then
        trace(PURE_FILE, "当前已经解锁德古拉展柜。");
        return false;
    end

    -- 标记解锁
    DungeonM.setDungeonMixedField("unlock_showcase", 1);

    -- 转换成商店
    local toElement = dbase.trans_element;
    local toClass = DungeonM.queryElement(toElement, "class");
    local para = { ["class"] = toClass, ["element"] = toElement };
    DungeonM.transformGrid(toClass, pos, GRID_STATE_OPEN, para);

    -- 扣除道具
    ItemM.costAmount(ME.user, sealItemId, 1);

    -- 抛出事件
    EventMgr.fire(event.UNLOCK_SHOWCASE, { ["pos"] = pos, });
    return true;
end

-- 生成圣棺奖励
function generateCoffinBonus()
    local bonus = FormulaM.invoke("CALC_COFFIN_BONUS", ME.user);
    return bonus;
end

-- 领取圣棺的奖励
-- @param pos    圣棺格子位置
-- @param index  选择的奖励索引
function takeCoffinBonus(pos, index)
    local grid = DungeonM.getGridByPos(pos);
    if not grid then
        trace(PURE_FILE, "格子(%d)不存在。", pos);
        return false;
    end

    if grid.type ~= GRID_TYPE_COFFIN then
        trace(PURE_FILE, "格子(%d)不是圣棺。", pos);
        return false;
    end

    if grid.state == GRID_STATE_DISABLE then
        trace(PURE_FILE, "格子(%d)已失效。", pos);
        return false;
    end

    local bonusList = grid.bonus;
    if type(bonusList) ~= 'table' then
        trace(PURE_FILE, "格子(%d)奖励尚未生成。", pos);
        return false;
    end

    if index < 1 or index > #bonusList then
        trace(PURE_FILE, "奖励索引(%d)不存在。", index);
        return false;
    end

    -- 标记格子失效
    grid:changeState(GRID_STATE_DISABLE);

    -- 执行奖励
    local bonus = bonusList[index];
    BonusM.doBonus(bonus, "coffin_bonus");

    -- 天空副本的圣棺
    if grid.is_sky_coffin == 1 then
        DungeonM.setDungeonMixedField("sky_coffin_reward", 1);
    end

    -- 抛出事件
    EventMgr.fire(event.TAKE_COFFIN_BONUS, { ["pos"] = pos, ["bonus"] = bonus, });

    return true;
end
